package com.yihaodian.server.servlet.rest;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.yihaodian.cluster.Node;
import com.yihaodian.cluster.admin.ClusterAdmin;
import com.yihaodian.index.meta.shard.ShardId;

/**
 * 
 * rest/admin/shard
 * 
 * 
 * e.g http://127.0.0.1:8080/search/rest/admin/shard?opt=on&shardId=product_s0&
 * nodeId=127.0.0.1_8080
 * 
 */
public class ShardAdminServlet extends AbstractServlet {
	private static final Logger logger = Logger
			.getLogger(ShardAdminServlet.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	ClusterAdmin clusterAdmin = null;

	@Override
	public void init() throws ServletException {
		super.init();

		clusterAdmin = injector.getInstance(ClusterAdmin.class);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String returnJson = "{'respState':'OK'}";
		Node node = this.getNode(req);
		ShardId shardId = this.getShardId(req);
		boolean allNode = node == null;

		String path = req.getRequestURI();
		if (path != null && path.contains("admin/shard")) {
			String opt = req.getParameter("opt");
			try {
				if (opt.equals("on")) {
					clusterAdmin.enableShard(shardId, allNode, node);
				} else if (opt.equals("off")) {
					clusterAdmin.disableShard(shardId, allNode, node);
				} else if (opt.equals("add")) {
					if (node == null) {
						returnJson = "{'respState':'nodeId param must have when add a shard'}";
					} else {
						clusterAdmin.addShard(shardId, node);
					}
				} else if (opt.equals("remove")) {
					if (node == null) {
						returnJson = "{'respState':'nodeId param must have when remove a shard'}";
					} else {
						clusterAdmin.removeShard(shardId, node);
					}
				} else if (opt.equals("switch")) {
					String version = req.getParameter("version");

					clusterAdmin.setShardDataVersion(shardId, version);
				} else {
					returnJson = "{'respState':'opt must be on,off,add,remove,switch'}";
				}

			} catch (Exception e) {
				logger.error(e.getMessage(), e);

				returnJson = e.getMessage();
			}
		}

		super.respJson(req, resp, returnJson);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
